package com.example.common.service.impl;

import com.example.common.service.ImageManage;
import com.example.common.utils.MinioUtils;
import com.example.common.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/9/2 20:36
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ImageManager implements ImageManage {

    private final static String IMAGE_URL_PREFIX = "image_url:";

    private final RedisUtils redisUtils;
    private final MinioUtils minioUtils;
    @Override
    public String getImageUrl(String fileId) {
        String imageCacheKey = IMAGE_URL_PREFIX + fileId;

        // 查询缓存
        if (redisUtils.hasKey(imageCacheKey)) {
            return redisUtils.get(imageCacheKey);
        }

        // 查询url
        String imageUrl = null;
        try {
            imageUrl = minioUtils.getObjectUrl(fileId);
            // 存入缓存，有效期1天
            redisUtils.set(imageCacheKey, imageUrl, 1L, TimeUnit.HOURS);
            return imageUrl;
        } catch (Exception e) {
            log.error("图片丢失，imageUrl:{}", imageUrl);
        }
        return fileId;
    }

    @Override
    public List<String> getImageUrlList(List<String> fileIds) {
        List<String> imageUrls = new ArrayList<>();
        for (String fileId : fileIds) {
            imageUrls.add(getImageUrl(fileId));
        }
        return imageUrls;
    }
}
